package com.fq.ioc.xml;

import com.fq.ioc.constant.CommonConstant;
import com.fq.ioc.reflect.ObjectPool;
import com.fq.ioc.reflect.ObjectPoolBuilder;
import com.fq.ioc.utils.SimpleValueSetUtils;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.lang.reflect.Field;
import java.util.List;

/**
 * @author jifang
 * @since 16/1/18下午9:18.
 */
public class XmlParse {

    private static final ObjectPool POOL = ObjectPoolBuilder.init(null);

    public static Element parseBeans(String config) {
        try {
            return new SAXReader().read(ClassLoader.getSystemResource(config)).getRootElement();
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
    }

    public static void processObject(Element bean, List<? extends Element> properties)
            throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException {
        Class<?> clazz = Class.forName(bean.attributeValue(CommonConstant.CLASS));
        Object targetObject = clazz.newInstance();

        for (Element property : properties) {
            String fieldName = property.attributeValue(CommonConstant.NAME);
            Field field = clazz.getDeclaredField(fieldName);
            field.setAccessible(true);
            // 含有value属性
            if (property.attributeValue(CommonConstant.VALUE) != null) {
                SimpleValueSetUtils.setSimpleValue(field, targetObject, property.attributeValue(CommonConstant.VALUE));
            } else if (property.attributeValue(CommonConstant.REF) != null) {
                String refId = property.attributeValue(CommonConstant.REF);
                Object object = POOL.getObject(refId);
                field.set(targetObject, object);
            } else {
                throw new RuntimeException("neither value nor ref");
            }
        }

        POOL.putObject(bean.attributeValue(CommonConstant.ID), targetObject);
    }
}
